import React from 'react';
import { Layout, Breadcrumb, Tag, Button, Checkbox, Modal, Input, Select, Form, message, TreeSelect, Tree } from 'antd';
import { Link } from 'react-router';
import './backEnd.less';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const TreeNode = Tree.TreeNode;
const token = sessionStorage.getItem('token')

class backEndForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [], // 分类树形数据
            list: [], // 分类列表数据
            show: false, // 分类详情显示
            detail: {}, // 分类详情
            addVisible: false, // 新增模态框显示
            updateVisible: false, // 修改模态框显示
            publicState: '', // 公共模态框状态
            publicVisible: false, // 公共模态框显示
        }
    }

    componentDidMount() {
        this.getCategoriesTree()
    }

    // 获取后端分类树
    getCategoriesTree() {
        $.ajax({
            url: `${config.JuseProduct}/categories/getCategoriesTree`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取后端分类树', res)
                if (res.code === 200) {
                    const list = []
                    const loop = arr => {
                        arr.forEach(item => {
                            list.push(item)
                            if (item.son) {
                                item.son.forEach(value => {
                                    if (item.father) {
                                        value.father = [].concat(item.father)
                                        value.father.push(item.categoryRename || item.categoryName)
                                    } else {
                                        value.father = [item.categoryRename || item.categoryName]
                                    }
                                })
                                loop(item.son)
                            }
                        })
                    }
                    loop(res.data)
                    this.setState({
                        data: res.data,
                        list
                    })
                }
            }
        })
    }

    // 生成树形组件
    setTree() {
        const loop = item => {
            let title = item.categoryRename || item.categoryName
            if (item.state === 0) {
                title += '（未启用）'
            } else if (item.state === 2) {
                title += '（已停用）'
            }
            return <TreeNode title={title} key={item.categoryId}>
                {item.son && item.son.map(value => {
                    return loop(value)
                })}
            </TreeNode>
        }
        return this.state.data.map(item => {
            return loop(item)
        })
    }

    // 点击分类节点
    selectCategory(arr) {
        const categoryId = arr[0]
        let show = false
        let detail = {}
        if (categoryId) {
            show = true
            this.state.list.forEach(item => {
                if (item.categoryId === categoryId) {
                    detail = item
                }
            })
        }
        this.setState({
            show,
            detail
        })
    }

    // 显示新增分类模态框
    showAddCategory() {
        this.setState({
            addVisible: true
        })
    }

    // 新增分类
    addCategory() {
        const form = this.props.form
        form.validateFields(['addCategoryName'], (err, values) => {
            if (!err) {
                Modal.confirm({
                    title: '确认是否保存该分类？',
                    onOk: () => {
                        $.ajax({
                            url: `${config.JuseProduct}/categories/addCategory`,
                            type: 'post',
                            headers: {
                                'Authorization': 'Bearer ' + token,
                            },
                            data: {
                                fatherId: this.state.detail.categoryId,
                                categoryName: values.addCategoryName
                            },
                            success: res => {
                                console.log('新增分类', res)
                                let value = form.getFieldValue('addCategoryName')
                                let errors = ''
                                if (res.code === 200) {
                                    this.getCategoriesTree()
                                    this.setState({
                                        addVisible: false
                                    })
                                    return form.resetFields(['addCategoryName'])
                                } else if (res.code === 201) {
                                    errors = '分类名称不能为空！'
                                } else if (res.code === 202) {
                                    errors = '分类名称只支持中文名、字母、阿拉伯数字、下划线、()，请核对后重新输入！'
                                } else if (res.code === 203) {
                                    errors = '最多6级分类！'
                                } else if (res.code === 204) {
                                    errors = '分类名称重复！'
                                }
                                form.setFields({
                                    addCategoryName: { value, errors: [errors] }
                                })
                            }
                        })
                    }
                })
            }
        })
    }

    // 隐藏新增分类模态框
    hiddenAddCategory() {
        this.setState({
            addVisible: false
        })
        this.props.form.resetFields(['addCategoryName'])
    }

    // 显示上一级分类
    showFather() {
        let detail = this.state.detail
        if (detail.father) {
            const father = [].concat(detail.father)
            father.push(detail.categoryRename || detail.categoryName)
            return father.join('>')
        } else {
            return detail.categoryRename || detail.categoryName
        }
    }

    // 验证分类名称
    validatorCategoryName(rule, value, callback) {
        const reg = /^[\u4e00-\u9fa5a-zA-Z\d_()]+$/
        if (value && !reg.test(value)) {
            callback('分类名称只支持中文名、字母、阿拉伯数字、下划线、()，请核对后重新输入！')
        } else {
            callback()
        }
    }

    // 显示修改分类模态框
    showUpdateCategory() {
        if (this.state.show) {
            const { detail } = this.state
            let title
            if (detail.state === 1) {
                return message.error('该分类已启用，系统无法进行修改！')
            } else if (detail.state === 2 && detail.relationState) {
                return message.error('该分类已在前端与后端分类对应管理模块进行对应，请解除对应关系后再进行修改！')
            } else if (detail.state === 2 && !detail.relationState) {
                title = '该分类已停用,确认是否修改？'
            } else {
                title = '确认是否修改？'
            }
            Modal.confirm({
                title,
                onOk: () => {
                    this.setState({
                        updateVisible: true
                    })
                    this.props.form.setFieldsValue({
                        updateCategoryName: detail.categoryRename || detail.categoryName
                    })
                }
            })
        }
    }

    // 修改分类
    updateCategory() {
        const form = this.props.form
        form.validateFields(['updateCategoryName'], (err, values) => {
            if (!err) {
                $.ajax({
                    url: `${config.JuseProduct}/categories/updateCategory`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId: this.state.detail.categoryId,
                        categoryName: values.updateCategoryName
                    },
                    success: res => {
                        console.log('修改分类', res)
                        let value = form.getFieldValue('updateCategoryName')
                        let errors = ''
                        if (res.code === 200) {
                            const detail = this.state.detail
                            if (detail.isSk) {
                                detail.categoryRename = values.updateCategoryName
                            } else {
                                detail.categoryName = values.updateCategoryName
                            }
                            return this.setState({
                                detail,
                                updateVisible: false
                            })
                        } else if (res.code === 201) {
                            errors = '分类名称不能为空！'
                        } else if (res.code === 202) {
                            errors = '分类名称只支持中文名、字母、阿拉伯数字、下划线、()，请核对后重新输入！'
                        } else if (res.code === 203) {
                            errors = '该分类已启用，系统无法进行修改！'
                        } else if (res.code === 204) {
                            errors = '分类名称重复！'
                        } else if (res.code === 205) {
                            errors = '该分类下已存在商品，无法进行修改操作！'
                        }
                        form.setFields({
                            updateCategoryName: { value, errors: [errors] }
                        })
                    }
                })
            }
        })
    }

    // 隐藏修改分类模态框
    hiddenUpdateCategory() {
        this.setState({
            updateVisible: false
        })
    }

    // 显示公共模态框
    showPublic(publicState) {
        this.state.show && this.setState({
            publicState,
            publicVisible: true
        })
    }

    // 显示公共模态框标题
    showTitle() {
        const publicState = this.state.publicState
        let title = ''
        switch (publicState) {
            case 1:
                title = '删除'
                break
            case 2:
                title = '启用'
                break
            case 3:
                title = '停用'
                break
        }
        return title
    }

    // 隐藏公共模态框
    hiddenPublic() {
        this.setState({
            publicVisible: false
        })
    }

    // 公共模态框确定事件
    confirmPublic() {
        const categoryId = this.state.detail.categoryId
        switch (this.state.publicState) {
            case 1:
                $.ajax({
                    url: `${config.JuseProduct}/categories/delCategory`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId
                    },
                    success: res => {
                        console.log('删除后端分类', res)
                        if (res.code === 200) {
                            this.getCategoriesTree()
                            this.setState({
                                publicVisible: false,
                                detail: {},
                                show: false
                            })
                        } else if (res.code === 202) {
                            message.error('该分类已使用，系统无法进行删除！')
                        }
                    }
                })
                break
            case 2:
                $.ajax({
                    url: `${config.JuseProduct}/categories/useCategory`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId
                    },
                    success: res => {
                        console.log('启用后端分类', res)
                        if (res.code === 200) {
                            const detail = this.state.detail
                            detail.state = 1
                            this.setState({
                                publicVisible: false,
                                detail
                            })
                        }
                    }
                })
                break
            case 3:
                $.ajax({
                    url: `${config.JuseProduct}/categories/stopCategory`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId
                    },
                    success: res => {
                        console.log('停用后端分类', res)
                        if (res.code === 200) {
                            const detail = this.state.detail
                            detail.state = 2
                            this.setState({
                                publicVisible: false,
                                detail
                            })
                        }
                    }
                })
                break
        }
    }

    // 同步分类
    syncCategories() {
        $.ajax({
            url: `${config.JuseProduct}/categories/syncCategories`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('同步分类', res)
                if (res.code === 200) {
                    this.getCategoriesTree()
                    this.setState({
                        show: false,
                        detail: {}
                    })
                }
            }
        })
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const detail = this.state.detail
        return (
            <Form>
                <div className='goods-label' style={{ minWidth: 1250 }}>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                                <Breadcrumb.Item>后端分类管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='clearfix'>
                            <div className='chengge-e'>
                                <Button className='member-button-aa' type='primary' onClick={this.showAddCategory.bind(this)} style={{ marginLeft: 20 }}>新增</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showUpdateCategory.bind(this)}>修改</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showPublic.bind(this, 1)}>删除</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showPublic.bind(this, 2)} > 启用</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showPublic.bind(this, 3)}> 停用</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.syncCategories.bind(this)}> 同步</Button>
                            </div>
                        </div>
                        <div className='clearfix backendt'>
                            <div className='backend-left'>
                                <Tree onSelect={this.selectCategory.bind(this)}>
                                    {this.setTree()}
                                </Tree>
                            </div>
                            <div className='backend-right'>
                                {
                                    this.state.show && <div className='backtoo'>
                                        <h1>分类信息:</h1>
                                        <ul>
                                            <li>分类编号：{detail.categoryCode}</li>
                                            {
                                                detail.father && <li>
                                                    上级分类：{detail.father.join('>')}
                                                </li>
                                            }
                                            <li>分类名称：{detail.categoryRename || detail.categoryName}</li>
                                            <li>分类来源：{detail.source}</li>
                                        </ul>
                                    </div>
                                }
                            </div>
                        </div>
                    </div>
                    <Modal
                        title={this.state.show ? '新增分类' : '新增'}
                        visible={this.state.addVisible}
                        onOk={this.addCategory.bind(this)}
                        onCancel={this.hiddenAddCategory.bind(this)}
                        maskClosable={false}
                    >
                        <div style={{ marginTop: 20 }}>
                            {
                                this.state.show && <FormItem
                                    {...formItemLayout}
                                    label="上级分类"
                                    style={{ marginTop: 20, marginBottom: 10 }}
                                >
                                    <p >
                                        {this.showFather()}
                                    </p>
                                </FormItem>
                            }
                            <FormItem
                                {...formItemLayout}
                                label="分类名称"
                                hasFeedback
                            >
                                {getFieldDecorator('addCategoryName', {
                                    rules: [{
                                        required: true,
                                        message: '分类名称不能为空'
                                    }, {
                                        validator: this.validatorCategoryName
                                    }],
                                })(
                                    <Input placeholder="请输入分类名称" />
                                )}
                            </FormItem>
                        </div>
                    </Modal>
                    <Modal
                        title="修改分类"
                        visible={this.state.updateVisible}
                        onOk={this.updateCategory.bind(this)}
                        onCancel={this.hiddenUpdateCategory.bind(this)}
                        maskClosable={false}
                    >
                        <div style={{ marginTop: 20 }}>
                            {
                                this.state.detail.father && <FormItem
                                    {...formItemLayout}
                                    label="上级分类"
                                    style={{ marginTop: 20, marginBottom: 10 }}
                                >
                                    <div>
                                        <p>{this.state.detail.father.join('>')}</p>
                                    </div>
                                </FormItem>
                            }
                            <FormItem
                                {...formItemLayout}
                                label="分类名称"
                                hasFeedback
                            >
                                {getFieldDecorator('updateCategoryName', {
                                    rules: [{
                                        required: true,
                                        message: '分类名称不能为空'
                                    }, {
                                        validator: this.validatorCategoryName
                                    }],
                                })(
                                    <Input placeholder="请输入分类名称" />
                                )}
                            </FormItem>
                        </div>
                    </Modal>
                    <Modal
                        title={this.showTitle()}
                        visible={this.state.publicVisible}
                        onOk={this.confirmPublic.bind(this)}
                        onCancel={this.hiddenPublic.bind(this)}
                        maskClosable={false}
                    >
                        <div className='detleti'>
                            {this.state.publicState === 1 && <p>确认是否删除该分类？</p>}
                            {this.state.publicState === 2 && <p>确认是否启用该分类？</p>}
                            {this.state.publicState === 3 && <p>确认是否停用该分类？</p>}
                        </div>
                    </Modal>
                </div>
            </Form>
        )
    }
}

const BackEnd = Form.create()(backEndForm);
export default BackEnd;